#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))

from utils import ResterHelper
from utils import ResterStringBuilder

VMA_SIZE_KEYS = ("Size", "Rss", "Pss", "Swap", "SwapPss", "Shared_Clean", "Shared_Dirty", "Private_Clean", "Private_Dirty", "Referenced", "Anonymous", "KernelPageSize", "MMUPageSize", "LazyFree", "AnonHugePages", "ShmemPmdMapped", "Shared_Hugetlb", "Private_Hugetlb", "Locked", "THPeligible", "FilePmdMapped" )

VMA_ADDR_KEYS = ("start", "end", "perm", "offset", "dev", "idx")

class ProcessObjectResults(ResterStringBuilder):
	def __init__(self, keys, row):
		for idx, key in enumerate(keys):
			self[key] = row[idx]

	def getStr(self, xargs=None, keys=None):
		ordered_keys = ("id", "name", "processes") + VMA_SIZE_KEYS
		return ResterStringBuilder.getStr(self, xargs, ordered_keys)

class ProcessesOfObjectResults(ResterStringBuilder):
	def __init__(self, keys, row):
		for idx, key in enumerate(keys):
			self[key] = row[idx]

	def getStr(self, xargs=None, keys=None):
		ordered_keys = ("id", "pid", "name", "process", "vmas") + VMA_SIZE_KEYS
		return ResterStringBuilder.getStr(self, xargs, ordered_keys)

class ProcessObjectsRestMgr(object):
	def __init__(self, product):
		self._product = product

	def get_all(self, xargs=None):
		keys = ("id", "name", "processes") + VMA_SIZE_KEYS
		sqlcmd = "select %s from objects" % ", ".join(keys)
		cursor = self._product.getCursor()
		cursor.execute(sqlcmd)

		processes = []
		for row in cursor:
			processes.append(ProcessObjectResults(keys, row))
		return processes

	def doRestRequest(self, id, mod, args):
		mCmdMap = {
			'processes':self._dbGetObjectProcesses
		}
		vals = mCmdMap[mod](id, args)
		return ResterHelper.build_array_content(vals, args)

	def _dbGetObjectProcesses(self, id, args):
		keys = ("id", "pid", "name", "process", "vmas") + VMA_SIZE_KEYS
		sqlcmd = "select %s from smaps_details where object_id=%d" % (", ".join(keys), int(id))
		cursor = self._product.getCursor()
		cursor.execute(sqlcmd)

		objects = []
		for row in cursor:
			objects.append(ProcessesOfObjectResults(keys, row))
		return objects

if __name__ == "__main__":
	import products

	product_mgr = products.Products()
	prod = product_mgr.get_product_by_name("openharmony", "rk3568")
	prod.load_db()

	mgr = ProcessObjectsRestMgr(prod)
	print(mgr.get_all())

	#print(mgr._dbGetProcessObjects(1, {}))
	#print(mgr._dbGetProcessVmas(1, {}))

	#print(mgr.doRestRequest(1, "objects", {}))

